package net.bwie.realtime.vehicle2.job;

import com.alibaba.fastjson.JSON;
import net.bwie.realtime.jtp.common.utils.JdbcUtil;
import net.bwie.realtime.jtp.common.utils.KafkaUtil;
import net.bwie.realtime.vehicle2.bean.TripMetrics;
import net.bwie.realtime.vehicle2.bean.VehicleData;
import net.bwie.realtime.vehicle2.function.ItineraryAnalysisFunction;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;


/**
 * 车辆行程分析作业类，用于处理车辆实时数据并进行行程统计分析
 */
public class ItineraryAnalysisJob {
    /**
     * 主方法，执行车辆行程分析作业
     */
    public static void main(String[] args) throws Exception {
        // 1、设置执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2、读取数据 kafka
        DataStream<String> kafkaStream = KafkaUtil.consumerKafka(env, "vehicle-data-log");
        // 3、处理数据
        DataStream<String> processStream = handle(kafkaStream);
        // 4、写入数据 clickhouse
        JdbcUtil.sinkToClickhouseUpsert(processStream, "INSERT INTO vehicle_data.dws_itineraryanalysis (vin, startTime, endTime,distance,duration,vgSpeed,maxSpeed,speeding)\n" +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        // 5、执行程序
        env.execute("ItineraryAnalysisJob");
    }

    private static DataStream<String> handle(DataStream<String> kafkaStream) {
        // 转换为VehicleData对象
        SingleOutputStreamOperator<VehicleData> map = kafkaStream.map(o -> JSON.parseObject(o, VehicleData.class));
        // 设置水位线
        DataStream<VehicleData> vehicleDataStream = map.assignTimestampsAndWatermarks(WatermarkStrategy
                .<VehicleData>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                .withTimestampAssigner(
                        new SerializableTimestampAssigner<VehicleData>() {
                            @Override
                            public long extractTimestamp(VehicleData element, long recordTimestamp) {
                                return element.getTimestamp();
                            }
                        }
                )
        );
        // 根据车辆vin码分组
        KeyedStream<VehicleData, String> vehicleDataStringKeyedStream = vehicleDataStream.keyBy(VehicleData::getVin);
        // 开窗  会话窗口
        WindowedStream<VehicleData, String, TimeWindow> window = vehicleDataStringKeyedStream.window(
                EventTimeSessionWindows.withGap(Time.minutes(10)
                )
        );
        // 行程分析处理
        DataStream<String> windowedMetrics = window.process(new ItineraryAnalysisFunction());
        windowedMetrics.print();

        return windowedMetrics;
    }
}
